package com.ruoyi.web.controller.system;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.SysPermissionService;

/**
 * 认证相关
 */
@RestController
@RequestMapping("/api/v1/auth")
public class SysAuthController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 获取用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser != null)
        {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("user", loginUser.getUser());
            ajax.put("roles", loginUser.getUser().getRoles());
            ajax.put("permissions", loginUser.getPermissions());
            return ajax;
        }
        return AjaxResult.error("获取用户信息失败");
    }

    /**
     * 获取路由信息
     */
    @GetMapping("/getRouters")
    public AjaxResult getRouters(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser != null)
        {
            // 用户菜单权限
            return AjaxResult.success(permissionService.getMenuRouters(loginUser.getUser().getUserId()));
        }
        return AjaxResult.error("获取路由信息失败");
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser != null)
        {
            tokenService.delLoginUser(loginUser.getToken());
        }
        return AjaxResult.success(MessageUtils.message("user.logout.success"));
    }
}